package com.itheima.d1_collection_set;

import com.itheima.d1_collection_set.bean.Student;

import java.util.Comparator;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * 目标：掌握TreeSet集合的使用。
 */
public class SetTest4 {
    public static void main(String[] args) {
        //什么叫元素具有默认排序？
        //   ·如果元素的类型实现了Comparable接口，意味着该元素具有默认的排序能力

        TreeSet<Integer> ids = new TreeSet<>();
        ids.add(3);
        ids.add(1);
        ids.add(1);
        ids.add(2);
        ids.add(4);
        System.out.println("ids = " + ids);
        //[1, 2, 3, 4]   去重、排序


        //TreeSet存储指定类型的对象，如果要有排序的能力，必须要实现Comparable接口，并重写compareTo方法，去指定排序的规则
        //要让学生按照年龄升序排序
        TreeSet<Student> students = new TreeSet<>();
        students.add(new Student("张三", 18, 185));
        students.add(new Student("李四", 19, 166));
        students.add(new Student("王五", 16, 158));
        System.out.println("students = " + students);

        //如果元素类型默认的排序规则不是我想要的或者类型不具备默认排序的能力，又不能去更改代码
        //则需要手动提供一个比较器给TreeSet

//        //TreeSet(Comparator comparator)
//        TreeSet<Student> students1 = new TreeSet<>(new Comparator<Student>() {
//            @Override
//            public int compare(Student o1, Student o2) {
//                return Double.compare(o1.getHeight(),o2.getHeight());
//            }
//        });

        //TreeSet(Comparator comparator)
        TreeSet<Student> students1 = new TreeSet<>((o1, o2) -> Double.compare(o1.getHeight(),o2.getHeight()));

        students1.add(new Student("张三", 18, 165));
        students1.add(new Student("李四", 19, 160));
        students1.add(new Student("王五", 16, 164));
        System.out.println("students1 = " + students1);


        /*
        * TreeSet是怎么去去重的？
        *   ·TreeSet去重和hashCode和equals方法没有关系 ---> 去重的依据是排序规则是否会返回0
        * */
        TreeSet<Teacher> teachers = new TreeSet<>();
        teachers.add(new Teacher("张三", 18));
        teachers.add(new Teacher("李四", 18));
        teachers.add(new Teacher("王五", 20));
        teachers.add(new Teacher("赵六", 25));
        System.out.println("teachers = " + teachers);
        //[Teacher{name='张三', age=18}, Teacher{name='王五', age=20}, Teacher{name='赵六', age=25}]
    }
}

class Teacher implements Comparable<Teacher>{
    String name;
    int age;

    public Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Teacher o) {
        return Integer.compare(age, o.age);
//        return 0; //结果：teachers = [Teacher{name='张三', age=18}]
    }
}